#include "Fingerprint-manager.h"
#include <functional>
#define ISCAR 1
FingerprintManager::FingerprintManager(FingerPrintDevice *fingerPrintDevice)
{
    this->verifyThreadPauseFlag = false;
    this->fingerPrintDevice = fingerPrintDevice;
    // 默认开启指纹比对线程
    this->verifyLoopThread = new thread(std::bind(&FingerprintManager::verfiyFingerPrintTaskRun, this));
}

void FingerprintManager::verfiyFingerPrintTaskRun(void)
{
    while (1)
    {
        printf("verfiy FingerPrint Task Run-------\n");
        // 线程暂停等待
        while (verifyThreadPauseFlag)
        {
            // wait 条件变量
            // 线程阻塞
            unique_lock<mutex> lock(verifyMutex); // 获取锁
            printf("线程阻塞-------\n");
            verifyCond.wait(lock);
        }
#if ISCAR   
        //小车上的代码
        bool touchState = fingerPrintDevice->isTouchState();
        if (touchState)
        {
            uint16_t pos = 0;
            bool ok = fingerPrintDevice->verfiyFingerPrint(pos);
            cout << "verfiy fingerprint ok" << " pos : " << pos << endl;
        }
        else
        {
            sleep(1);
            continue;
        }
#else
        // pc上的代码
        uint16_t pos = 0;
        bool ok = fingerPrintDevice->verfiyFingerPrint(pos);
        cout << "verfiy fingerprint ok: " << ok << " pos : " << pos << endl;
        sleep(1);
#endif
    }
}

void FingerprintManager::pauseVerifyFingerPrintTask(void)
{
    verifyThreadPauseFlag = true;
    // 获取锁如果没获取到就一直阻塞
    unique_lock<mutex> lock(verifyMutex);
}

void FingerprintManager::resumeVerifyFingerPrintTask(void)
{
    verifyThreadPauseFlag = false;
    verifyMutex.lock();
    verifyCond.notify_one();
    verifyMutex.unlock();
}

// 录入指纹
bool FingerprintManager::recordFingerPrint(const uint16_t pos)
{
    bool touchState = false;
    // 暂停比对
    pauseVerifyFingerPrintTask();

// 检查是否手指是否按在触摸板上
#if ISCAR 
    //小车上的代码
    for (int i = 0; i < 5; i++)
    {
        touchState = fingerPrintDevice->isTouchState();
        if (touchState)
        {
            break;
        }
        sleep(1);
    }

    bool ok = false;
    if (touchState)
    {
        // 录入指纹
        ok = fingerPrintDevice->recordFingerprint(pos);
    }
#else
    // pc上使用
    bool ok = fingerPrintDevice->recordFingerprint(pos);
#endif
    // 恢复比对
    resumeVerifyFingerPrintTask();

    return true;
}

// 删除指纹
bool FingerprintManager::deleteFingerPrint(const uint16_t pos)
{
    // 暂停比对
    pauseVerifyFingerPrintTask();
    bool ok = fingerPrintDevice->deleteFingerprint(pos);
    // 恢复比对
    resumeVerifyFingerPrintTask();
    return ok;
}

// 清空指纹库
bool FingerprintManager::clearFingerPrintlib(void)
{
    // 暂停比对
    pauseVerifyFingerPrintTask();
    bool ok = fingerPrintDevice->clearFingerPrintLib();
    // 恢复比对
    resumeVerifyFingerPrintTask();
    return ok;
}
